﻿using System;

namespace ControleRepresentante.Data.Helpers
{
    internal class CatalogStepHelper
    {
        private readonly IDataAccess m_DataAccess;

        internal CatalogStepHelper(IDataAccess dataAccess)
        {
            m_DataAccess = dataAccess;
        }

        internal TableHelper CreateTable(string tableName, bool isIdLong = false, string idColumnName = "Id")
        {
            string id = isIdLong
                ? "({0} BIGINT IDENTITY(1,1) NOT NULL PRIMARY KEY)" 
                : "({0} {1} NOT NULL PRIMARY KEY)";
            
            id = String.Format(id, idColumnName, m_DataAccess.GetTypeName(ColumnType.Guid));
            
            m_DataAccess.ExecuteCommand(String.Format(@"
                CREATE TABLE {0}
                {1}",
                tableName, id));
            return GetTable(tableName);
        }

        internal TableHelper CreateTableToTable(string tableName, string columnName1, ColumnType columnType1, string tableName1, string primaryKey1, string columnName2, ColumnType columnType2, string tableName2, string primaryKey2)
        {
            m_DataAccess.ExecuteCommand(String.Format(@"
                CREATE TABLE {0}
                (
                    {1} {2} NOT NULL,
                    {5} {6} NOT NULL,
                    FOREIGN KEY ({1}) REFERENCES {3}({4}),
                    FOREIGN KEY ({5}) REFERENCES {7}({8})
                )",
                tableName,
                columnName1, m_DataAccess.GetTypeName(columnType1), tableName1, primaryKey1,
                columnName2, m_DataAccess.GetTypeName(columnType2), tableName2, primaryKey2));
            return GetTable(tableName);
        }

        internal TableHelper GetTable(string tableName)
        {
            return new TableHelper(tableName, m_DataAccess);
        }
    }
}